package com.zzb.projectfactory.framework.role.service;

import com.alibaba.fastjson.JSON;
import com.zzb.projectfactory.framework.common.BaseResponse;
import com.zzb.projectfactory.framework.common.BaseService;
import com.zzb.projectfactory.framework.common.DaoException;
import com.zzb.projectfactory.framework.common.ServiceException;
import com.zzb.projectfactory.framework.event.EventHome;
import com.zzb.projectfactory.framework.role.dao.UserDAO;
import com.zzb.projectfactory.framework.role.dao.jpa.UserRepository;
import com.zzb.projectfactory.framework.role.entity.User;
import com.zzb.projectfactory.framework.role.event.LoginSuccessEvent;
import com.zzb.projectfactory.framework.role.form.UserLoginForm;
import com.zzb.projectfactory.framework.utils.Misc;
import com.zzb.projectfactory.framework.validator.annotation.ValidatorEnabled;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 用户账号 service类
 */
@Service
public class UserService extends BaseService<UserDAO, User, UserRepository> {
    private static final Logger logger = LoggerFactory.getLogger(UserService.class);
    @Autowired
    private UserDAO userDAO;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysRoleUserService sysRoleUserService;

    @Override
    public UserDAO getDAO() {
        return userDAO;
    }

    @ValidatorEnabled
    public BaseResponse<User> saveUser(User user, User operator) throws ServiceException {
        logger.info("正在保存用户["+ JSON.toJSONString(user)+"]["+JSON.toJSONString(operator)+"]");

        if(StringUtils.isEmpty(user.getId()) && findByusername(user.getUsername())!= null){
            return new BaseResponse<>(BaseResponse.FAIL,"保存用户失败，用户名不能重复");
        }
        user.setPassword(Misc.generatePassword(user.getPassword()));
        BaseResponse<User> createRet = createOrUpdate(user, operator);
        return createRet;
    }

    public BaseResponse<User> login(UserLoginForm userLoginForm, String ip){
        try {
            User user = getDAO().getByUsernameAndPassword(userLoginForm.getUsername(), userLoginForm.getPassword());
            if(!user.getActivate()){
                return new BaseResponse<>(BaseResponse.FAIL,"登录失败，该用户已被屏蔽",user);
            }

            //登陆成功发布事件
            LoginSuccessEvent event = new LoginSuccessEvent();
            event.setIp(ip);
            event.setUser(user);
            event.setLoginDate(new Date());
            EventHome.publishEvent(event);
            return new BaseResponse<>(BaseResponse.SUCCESS,"登录成功",user);
        } catch (DaoException e) {
            return new BaseResponse<>(BaseResponse.FAIL,e.getMessage());
        }
    }

    public BaseResponse deleteUser(String id,User operate) throws ServiceException{
        //删除用户权限
        sysRoleUserService.deleteByUserId(id);
        return delete(id);
    }

    public User findByusername(String name){
        List<User> userList = userDAO.getRepository().findByUsername(name);
        if(CollectionUtils.isNotEmpty(userList)) return userList.get(0);
        return null;
    }


}
